package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;
import com.lagou.rpc.pojo.ServerAddress;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
public class RpcClientProxy {
    private static int index;

    private static List<ServerAddress> serverAddressList = new ArrayList<>();

    public static void addServerAddress(String ip, int port){
        ServerAddress serverAddress = new ServerAddress();
        serverAddress.setIp(ip);
        serverAddress.setPort(port);
        serverAddressList.add(serverAddress);
    }

    public static Object createProxy(Class serviceClass){
        addServerAddress("127.0.0.1",8899);
        addServerAddress("127.0.0.1",8888);
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {


                        //1.封装request请求
                        RpcRequest rpcRequest = new RpcRequest();

                        //设置请求唯一标识
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        //设置类名
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        //设置方法名
                        rpcRequest.setMethodName(method.getName());
                        //设置参数类型
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        //设置参数
                        rpcRequest.setParameters(args);

                        //2.创建RpcClient对象
                        if(serverAddressList.size() == 0){
                            throw new RuntimeException("无连接的服务");
                        }

                        index = (index+1)% serverAddressList.size();
                        ServerAddress serverAddress = serverAddressList.get(index);
                        RpcClient rpcClient = new RpcClient(serverAddress.getIp(),serverAddress.getPort());

                        try {
                            //3.发送消息
                            Object rpcResponseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));

                            RpcResponse rpcResponse = JSON.parseObject(rpcResponseMsg.toString(), RpcResponse.class);

                            //判断消息是否发送成功,失败抛出错误
                            if(rpcResponse.getError() != null){
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();

                            return JSON.parseObject(result.toString(), method.getReturnType());
                        }catch (Exception e){
                            throw e;
                        }finally {
                            //关闭客户端，释放资源
                            rpcClient.close();
                        }


                    }
                }

        );
    }
}
